package com.laity.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author: Laity
 * @Project: JavaLaity
 * @Package: com.laity.forkjoin.ExecuteDemo
 * @Date: 2023年12月04日 10:58
 * @Description: 模拟执行任务
 * @Version: 1.0
 */

public class ExecuteDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        // 执行任务
        test3();
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
    }

    // 普通程序员 491
    public static void test1() {
        long sum = 0L;
        for (long i = 1L; i <= 10_0000_0000L; i++) {
            sum += i;
        }
        System.out.println(sum);
    }

    // 使用ForkJoin
    public static void test2() throws ExecutionException, InterruptedException {
        ForkJoinPool joinPool = new ForkJoinPool();

        // joinPool.execute(new ForkJoinDemo(1L, 10_0000_0000L)); // 同步执行任务;无法获取结果
        ForkJoinTask<Long> task = joinPool.submit(new ForkJoinDemo(0L, 10_0000_0000L));// 异步执行任务
        System.out.println(task.get());
        /*
        125000000250000000
        125000000250000000
        250000000500000000
        耗时：2632
         */
    }

    // Stream流 并行流 - 最佳方案 331
    public static void test3() {
        long reduce = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0L, Long::sum);
        System.out.println(reduce);
    }
}
